<template>
  <div>
    <h2>容器管理</h2>
    <p>欢迎来到容器管理页面！</p>
  </div>
  <div>
    <el-button type="primary" @click="$router.push('/ImagesManage')">前往镜像管理</el-button>
    <el-button type="success" @click="$router.push('/settings')">前往设置</el-button>
  </div>
  <!-- <div>
    <el-button type="info" @click="showLocalContainers">显示容器</el-button>
  </div> -->
  <p> 本地容器查询结果：</p>
  <!-- <el-radio-group v-model="tableLayoutcontainer">
    <el-radio-button value="fixed">fixed</el-radio-button>
    <el-radio-button value="auto">auto</el-radio-button>
  </el-radio-group> -->
  <div>

  
  <!-- 骨架屏 -->
    <!-- <el-skeleton v-if="dockerContainerStore.loading" :rows="4" animated /> -->

  <el-table :data="tableDataLocalContainers" 
            v-loading="loading"
            element-loading-text="Loading..."
            style="width: 100%; height: 400px;"
            empty-text="">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="CONTAINER_ID" :label="$t('dockerContainers.container.id')" min-width= '200'show-overflow-tooltip/>
    <el-table-column prop="IMAGE" :label="$t('dockerContainers.container.image')" min-width= '250' show-overflow-tooltip/>
    <el-table-column prop="COMMAND" :label="$t('dockerContainers.container.command')" min-width= '200' show-overflow-tooltip/>
    <el-table-column prop="CREATED" :label="$t('dockerContainers.container.created')" min-width= '200' show-overflow-tooltip/>
    <el-table-column prop="STATUS" :label="$t('dockerContainers.container.status')" min-width= '150' show-overflow-tooltip/>
    <el-table-column prop="NAME" :label="$t('dockerContainers.container.names')" min-width= '100' show-overflow-tooltip/>
    <!-- 新增操作列 -->
  <el-table-column 
    :label="$t('dockerimages.image.actions')" 
    min-width="300"
    align="center"
  >
    <template #default="scope">
      
      <!-- 如果 status 为 running 显示停止按钮 -->
      <el-button 
        size="small"
        type="danger"
        v-if="scope.row.STATUS === 'running'"
        @click="handleStopContainer(scope.row)"
        round
      >
        {{ $t('dockerContainers.container.stop') }}
      </el-button>

      <!-- 如果 status 为 created或者exited 显示启动按钮 -->
      <el-button 
        size="small"
        type="success"
        v-else-if="scope.row.STATUS === 'created' || scope.row.STATUS === 'exited'"
        @click="handleStartContainer(scope.row)"
      round>
        {{ $t('dockerContainers.container.start') }}
      </el-button>
      <el-button 
        size="small" 
        type="primary"
        :disabled="scope.row.STATUS === 'created'"
        @click="viewLogs(scope.row)"
      round>
        {{ $t('dockerContainers.container.log') }}
      </el-button>
      <el-button 
        size="small" 
        type="primary" 
        @click="handleShowContainerDetails(scope.row)"
      round>
        {{ $t('dockerimages.image.details') }}
      </el-button>
      <el-dropdown trigger="click" size="small" style="margin-left: 10px;">
        <el-button type="primary" size="small" round>更多 <el-icon class="el-icon--right"><arrow-down /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item :icon="Plus">Action 1</el-dropdown-item>
            <el-dropdown-item :icon="CirclePlusFilled">Action 2</el-dropdown-item>
            <el-dropdown-item :icon="CirclePlus">Action 3</el-dropdown-item>
            <el-dropdown-item :icon="Check">Action 4</el-dropdown-item>
            <el-dropdown-item :icon="CircleCheck">Action 5</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </template>
  </el-table-column>
  <slot></slot>
  <!-- 空状态插槽 -->
  <template #empty>
    <el-empty v-if="!loading && dockerContainerStore.containersIsEmpty" description="暂无数据" />
  </template>
  </el-table>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, computed, type ComputedRef} from 'vue'
// import type { TableInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDockerContainerStore } from '@/stores/dockerContainer'
import { storeToRefs } from 'pinia'
import {
  ArrowDown,
  Check,
  CircleCheck,
  CirclePlus,
  CirclePlusFilled,
  Plus,
} from '@element-plus/icons-vue'
import { startContainer, stopContainer} from '@/api/docker'
import { useRouter } from 'vue-router'

const router = useRouter();
// const tableLayoutcontainer = ref<TableInstance['tableLayout']>('fixed')
const dockerContainerStore = useDockerContainerStore()
const { containers} = storeToRefs(dockerContainerStore)
const loading = ref(true)

function viewLogs(container: any) {
  router.push(`/logs/${container.CONTAINER_ID}`);
}

onMounted(() => {
  // const containersIsEmpty: ComputedRef<boolean> = computed(() => dockerContainerStore.containers.length === 0)
  // console.log('containersIsEmpty:', containersIsEmpty.value)
  setTimeout(() => {
    if (dockerContainerStore.containersIsEmpty){
      console.log('容器列表为空，正在获取容器列表...')
      showLocalContainers()
      console.log('容器列表获取完成。')
    }
    loading.value = false
  }, 300);
})

// 计算属性转换数据格式
const tableDataLocalContainers = computed(() => {
  return containers.value.map(con => ({
    CONTAINER_ID: formatContainerID(con.CONTAINER_ID) || con.name || '<none>',
    IMAGE: con.IMAGE || '<none>',
    COMMAND: con.COMMAND || '<none>',
    CREATED: formatUTCTime(con.CREATED),
    STATUS: con.STATUS || '<none>',
    NAME: con.NAME || '<none>',
  }))
})

// 处理启动容器操作
const handleStartContainer = async (container: any) => {
  console.log('准备启动容器:', container);
  const containerID= container.CONTAINER_ID
  try {
    console.log('准备启动容器:', containerID);
    const success = await startContainer(containerID);
    console.log('启动容器结果:', success);
    if (success.data.status === 'success') {
      ElMessage.success(`容器 ${containerID} 启动成功`);
      // 刷新容器列表
      await showLocalContainers();
    } else {
      ElMessage.error(`容器 ${containerID} 启动失败: ` + (success.data.message || dockerContainerStore.error || '未知错误'));
    }
  } catch (error) {
    ElMessage.error(`容器 ${containerID} 启动失败: ` + (error as Error).message);
  }
}

// 处理停止容器操作
const handleStopContainer = async(container: any) => {
  console.log('准备停止容器:', container);
  const containerID= container.CONTAINER_ID
  try {
    const success = await stopContainer(containerID);
    if (success.data.status === 'success') {
      ElMessage.success(`容器 ${containerID} 停止成功`);
      // 刷新容器列表
      await showLocalContainers();
    } else {
      ElMessage.error(`容器 ${containerID} 停止失败: ` + (success.data.message || dockerContainerStore.error || '未知错误'));
    }
  } catch (error) {
    ElMessage.error(`容器 ${containerID} 停止失败: ` + (error as Error).message);
  }

}

// 处理删除容器操作
const handleRemoveContainer = async (container: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除容器 ${container.NAMES} 吗？`,
      '删除容器',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    const success = false
    if (success) {
      ElMessage.success('容器删除成功')
    } else {
      ElMessage.error('容器删除失败: 暂未实现API' + (dockerContainerStore.error || '未知错误'))
    }
  } catch (error) {
    ElMessage.info('已取消删除操作')
  }   
}
// 处理导出容器操作
const handleExportContainer = (container: any) => {
  ElMessage.info(`导出容器 ${container.NAMES} 功能暂未实现。`)
}

// 处理显示容器详情操作
const handleShowContainerDetails = (container: any) => {
  ElMessage.info(`显示容器 ${container.NAMES} 详情功能暂未实现。`)
}

// 点击按钮获取容器列表
const showLocalContainers = async () => {
  // 检查网络连接
  if (!window.navigator.onLine) {
    ElMessage.error('网络不可用，请检查您的连接。')
    return;
  }
  try {
    const success = await dockerContainerStore.fetchContainers()
    if (success && dockerContainerStore.containersIsEmpty === false) {
        ElMessage.success('获取容器成功')
    } else if (success && dockerContainerStore.containersIsEmpty === true){
      ElMessage.info('当前没有可用的容器')
    }else {
        ElMessage.error('获取容器失败: ' + (dockerContainerStore.error || '未知错误'))
    }
    
  } catch (error) {
    ElMessage.error('获取容器失败: ' + (error as Error).message)
  }
}

const formatContainerID = (Containerid: string) => {
  return Containerid.slice(0, 12)
}

// 辅助函数：格式化日期
const formatDate = (timestamp: number) => {
  // return new Date(timestamp * 1000).toLocaleString()
  // 检查时间戳单位并自动转换
  let actualTimestamp = timestamp;
  
  // 如果时间戳是10位数（秒级），转换为毫秒
  if (timestamp.toString().length === 10) {
    actualTimestamp = timestamp * 1000;
  }
  // 如果时间戳是13位数（毫秒级），直接使用
  else if (timestamp.toString().length === 13) {
    actualTimestamp = timestamp;
  }
  // 其他情况可能需要特殊处理
  else {
    console.warn('时间戳格式异常，请检查输入值:', timestamp);
  }
  
  const date = new Date(actualTimestamp);
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const formatUTCTime = (utcTimeString: string) => {
  const localTime = new Date(utcTimeString).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
  console.log('UTC Time:', utcTimeString);
  console.log('Local Time:', localTime);
  return localTime;
}
</script>
